package org.reptile.controller;

import org.reptile.model.User;
import org.reptile.response.ResponseObj;
import org.reptile.service.AnalyticService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author : lsliang
 * @Description :
 * @Date :  Create in 20:53 2017/12/15
 * @Modifyed By :
 */
@RestController
public class BallotController {

    @Resource
    private AnalyticService analyticService;

    @GetMapping(value = {"/getBallot", "/getBallot/{count}"})
    public ResponseObj<List<User>> getBallot(@PathVariable(value = "count", required = false)Integer count){
        ResponseObj<List<User>> obj = new ResponseObj<List<User>>();
        try {
            if (null == count){
                count = 10;
            } else if (count > 20){
                throw new RuntimeException("抱歉，暂时不支持查询排名20以后的人员");
            }
            List<User> users = analyticService.getUsers(count);
            obj.setData(users);
        } catch (Exception e) {
            obj.setSuccess(false);
            obj.setErrMsg("获取数据失败" + e.getMessage());
        }
        return obj;
    }

    /**
     * 通过名字获取排名信息
     * @param name
     * @return
     */
    @GetMapping(value = {"/getBallotByName/{name}"})
    public ResponseObj<Integer> getBallotByName(@PathVariable("name")String name){
        ResponseObj<Integer> obj = new ResponseObj<Integer>();
        try {
            List<User> users = analyticService.getUsers();
            boolean flag = false;
            int count = 1;
            for (User user : users){
                if (name.equals(user.getName())){
                    flag = true;
                    break;
                }else {
                    count++;
                }
            }
            if (flag){
                obj.setData(count);
            }else{
                throw new RuntimeException("抱歉未查询到该用户的排名信息");
            }
        } catch (Exception e) {
            obj.setSuccess(false);
            obj.setErrMsg("获取排名信息失败" + e.getMessage());
        }
        return obj;
    }
}
